package presentation.rest;

import com.sun.jersey.api.json.JSONWithPadding;

import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

public class ResponseBuilder {

	private HttpHeaders headers;
	private String callback;
	private Object entity;

	private ResponseBuilder() {

	}

	public static ResponseBuilder newBuilder() {
		return new ResponseBuilder();
	}

	public HttpHeaders getHeaders() {
		return headers;
	}

	public ResponseBuilder setHeaders(HttpHeaders headers) {
		this.headers = headers;
		return this;
	}

	public String getCallback() {
		return callback;
	}

	public ResponseBuilder setCallback(String callback) {
		this.callback = callback;
		return this;
	}

	public Object getEntity() {
		return entity;
	}

	public ResponseBuilder setEntity(Object entity) {
		this.entity = entity;
		return this;
	}

	public Response build() {
		boolean useJsonP = headers != null && headers.getAcceptableMediaTypes().contains(ServiceLocator.MEDIA_TYPE_X_JAVASCRIPT_TYPE);
		final Response.ResponseBuilder responseBuilder;

		if (useJsonP) {
			responseBuilder = Response
					.ok(new JSONWithPadding(entity, callback))
					.type(ServiceLocator.MEDIA_TYPE_X_JAVASCRIPT_TYPE);
		} else {
			responseBuilder = Response
					.ok(entity)
					.type(MediaType.APPLICATION_JSON_TYPE);
		}

		return responseBuilder.build();
	}
}
